// 表单验证和交互功能
class FormValidator {
    constructor(formSelector, options = {}) {
        this.form = document.querySelector(formSelector);
        this.options = {
            errorClass: 'error',
            successClass: 'success',
            ...options
        };
        
        if (this.form) {
            this.init();
        }
    }
    
    init() {
        this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        this.setupFieldValidation();
    }
    
    setupFieldValidation() {
        const fields = this.form.querySelectorAll('input, textarea, select');
        
        fields.forEach(field => {
            field.addEventListener('blur', () => this.validateField(field));
            field.addEventListener('input', () => this.clearFieldError(field));
        });
    }
    
    validateField(field) {
        const value = field.value.trim();
        const type = field.type;
        const required = field.hasAttribute('required');
        
        // 清除之前的错误
        this.clearFieldError(field);
        
        // 必填验证
        if (required && !value) {
            this.showFieldError(field, '此字段为必填项');
            return false;
        }
        
        // 邮箱验证
        if (type === 'email' && value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(value)) {
                this.showFieldError(field, '请输入有效的邮箱地址');
                return false;
            }
        }
        
        // 电话验证
        if (type === 'tel' && value) {
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(value)) {
                this.showFieldError(field, '请输入有效的手机号码');
                return false;
            }
        }
        
        // 长度验证
        const minLength = field.getAttribute('minlength');
        const maxLength = field.getAttribute('maxlength');
        
        if (minLength && value.length < parseInt(minLength)) {
            this.showFieldError(field, `最少需要 ${minLength} 个字符`);
            return false;
        }
        
        if (maxLength && value.length > parseInt(maxLength)) {
            this.showFieldError(field, `最多允许 ${maxLength} 个字符`);
            return false;
        }
        
        this.showFieldSuccess(field);
        return true;
    }
    
    showFieldError(field, message) {
        field.classList.add(this.options.errorClass);
        
        // 创建或更新错误消息
        let errorElement = field.parentNode.querySelector('.error-message');
        if (!errorElement) {
            errorElement = document.createElement('div');
            errorElement.className = 'error-message';
            field.parentNode.appendChild(errorElement);
        }
        errorElement.textContent = message;
        errorElement.style.display = 'block';
    }
    
    showFieldSuccess(field) {
        field.classList.remove(this.options.errorClass);
        field.classList.add(this.options.successClass);
        
        const errorElement = field.parentNode.querySelector('.error-message');
        if (errorElement) {
            errorElement.style.display = 'none';
        }
    }
    
    clearFieldError(field) {
        field.classList.remove(this.options.errorClass, this.options.successClass);
        
        const errorElement = field.parentNode.querySelector('.error-message');
        if (errorElement) {
            errorElement.style.display = 'none';
        }
    }
    
    validateForm() {
        const fields = this.form.querySelectorAll('input, textarea, select');
        let isValid = true;
        
        fields.forEach(field => {
            if (!this.validateField(field)) {
                isValid = false;
            }
        });
        
        return isValid;
    }
    
    async handleSubmit(e) {
        e.preventDefault();
        
        if (!this.validateForm()) {
            this.showFormError('请检查表单中的错误');
            return;
        }
        
        // 显示提交状态
        this.showSubmittingState();
        
        try {
            // 模拟API调用
            await this.submitForm();
            this.showFormSuccess('提交成功！我们会尽快与您联系。');
            this.form.reset();
        } catch (error) {
            this.showFormError('提交失败，请稍后重试');
        } finally {
            this.hideSubmittingState();
        }
    }
    
    async submitForm() {
        // 模拟网络请求
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                // 模拟90%的成功率
                if (Math.random() > 0.1) {
                    resolve();
                } else {
                    reject(new Error('Network error'));
                }
            }, 2000);
        });
    }
    
    showSubmittingState() {
        const submitBtn = this.form.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
        }
    }
    
    hideSubmittingState() {
        const submitBtn = this.form.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 提交';
        }
    }
    
    showFormSuccess(message) {
        this.showFormMessage(message, 'success');
    }
    
    showFormError(message) {
        this.showFormMessage(message, 'error');
    }
    
    showFormMessage(message, type) {
        // 移除之前的消息
        const existingMessage = this.form.querySelector('.form-message');
        if (existingMessage) {
            existingMessage.remove();
        }
        
        // 创建新消息
        const messageElement = document.createElement('div');
        messageElement.className = `form-message ${type}`;
        messageElement.textContent = message;
        
        this.form.insertBefore(messageElement, this.form.firstChild);
        
        // 自动移除消息
        setTimeout(() => {
            messageElement.remove();
        }, 5000);
    }
}

// 联系表单验证
document.addEventListener('DOMContentLoaded', function() {
    // 初始化联系表单验证
    const contactForm = new FormValidator('#contactForm');
    
    // 初始化订阅表单验证
    const newsletterForms = document.querySelectorAll('.newsletter-form');
    newsletterForms.forEach(form => {
        new FormValidator(form);
    });
    
    // 添加输入框焦点效果
    const inputs = document.querySelectorAll('input, textarea');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.parentNode.classList.add('focused');
        });
        
        input.addEventListener('blur', function() {
            if (!this.value) {
                this.parentNode.classList.remove('focused');
            }
        });
    });
});

// 文件上传功能
function initFileUpload() {
    const fileInputs = document.querySelectorAll('input[type="file"]');
    
    fileInputs.forEach(input => {
        input.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 验证文件大小 (5MB)
                if (file.size > 5 * 1024 * 1024) {
                    alert('文件大小不能超过5MB');
                    this.value = '';
                    return;
                }
                
                // 验证文件类型
                const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
                if (!allowedTypes.includes(file.type)) {
                    alert('只支持 JPG, PNG, GIF, PDF 格式的文件');
                    this.value = '';
                    return;
                }
                
                // 显示文件名
                const fileName = file.name;
                const fileLabel = this.parentNode.querySelector('.file-label');
                if (fileLabel) {
                    fileLabel.textContent = fileName;
                }
            }
        });
    });
}

// 自动保存表单数据
function initAutoSave() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        const formId = form.id || 'form_' + Math.random().toString(36).substr(2, 9);
        
        // 恢复保存的数据
        const savedData = localStorage.getItem(formId);
        if (savedData) {
            const data = JSON.parse(savedData);
            Object.keys(data).forEach(key => {
                const field = form.querySelector(`[name="${key}"]`);
                if (field) {
                    field.value = data[key];
                }
            });
        }
        
        // 监听输入变化并保存
        const inputs = form.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            input.addEventListener('input', function() {
                const formData = {};
                form.querySelectorAll('input, textarea, select').forEach(field => {
                    if (field.name) {
                        formData[field.name] = field.value;
                    }
                });
                localStorage.setItem(formId, JSON.stringify(formData));
            });
        });
        
        // 提交成功后清除保存的数据
        form.addEventListener('submit', function() {
            localStorage.removeItem(formId);
        });
    });
}

// 初始化所有表单功能
document.addEventListener('DOMContentLoaded', function() {
    initFileUpload();
    initAutoSave();
}); 